import svgCaptcha from 'svg-captcha'
import User from '../model/User'
import Sign from '../model/Sign'
import { setValue } from '../config/RedisConfig'
class PublicController {
  // 验证码接口
  async getCaptcha (ctx) {
    const body = ctx.request.query
    // 定义svg验证码的格式
    const newCaptcha = svgCaptcha.create({
      size: 4,
      ignoreChars: '0Oo1il',
      color: true,
      noise: Math.floor(Math.random() * 5),
      width: 150,
      height: 38
    })
    // 保存验证码10分钟
    setValue(body.sid, newCaptcha.text, 10 * 60)
    ctx.body = {
      code: 200,
      data: newCaptcha.data
    }
  }

  // 签到排行
  async getHotSignRecord (ctx) {
    // 0-总签到榜，1-最新签到
    const params = ctx.query
    const page = params.page ? parseInt(params.page) : 0
    const limit = params.limit ? parseInt(params.limit) : 10
    const index = params.index ? params.index : '0'
    let result
    let total = 0
    if (index === '0') {
      // 总签到榜
      result = await User.getTotalSign(page, limit)
      total = await User.getTotalSignCount()
    } else if (index === '1') {
      // 今日签到
      result = await Sign.getTopSign(page, limit)
      total = await Sign.getTopSignCount()
    } else if (index === '2') {
      // 最新签到
      result = await Sign.getLatestSign(page, limit)
      total = await Sign.getSignCount()
    }
    ctx.body = {
      code: 200,
      data: result,
      total,
      msg: '获取签到排行成功'
    }
  }
}
export default new PublicController()
